package com.etc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;

/**
 * @Auther: Wangcc
 * @Date: 2018/8/29 10:28
 * @Description: 连接池
 */
public class ConnectionPool {

    //静态的counnection队列
    private static LinkedList<Connection> connectionQueue;


    /**
     * 加载驱动
     */
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    public static synchronized  Connection getConnection(){

        try {
            if (connectionQueue == null){
                connectionQueue = new LinkedList<Connection>();
                for(int i = 0; i < 10; i++) {
                    Connection conn = DriverManager.getConnection(
                            "jdbc:mysql://localhost:3306/testdb",
                            "root",
                            "root");
                    connectionQueue.push(conn);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return connectionQueue.poll();
    }
    /**
     * 还回去一个连接
     */
    public static void returnConnection(Connection conn) {
        connectionQueue.push(conn);
    }
}
